<template>
  <div class="mybox">
    <el-form :inline="true" @submit.native.prevent>
      <el-form-item>
        <el-input
          v-model="keyword"
          @keyup.native.enter="initPage"
          placeholder="用户名"
          style="width: 20em; margin-right: 15px"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="default" @click="initPage">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="visibleFlag = true">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="是否确认删除选中的数据" @confirm="delSelect">
          <el-button type="danger" slot="reference" :disabled="selectFlag"
            >批量删除</el-button
          >
        </el-popconfirm>
      </el-form-item>
    </el-form>
    <el-table
      stripe
      border
      @select="selectCheck"
      @select-all="selectAll"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column align="center" prop="avatar" label="头像">
        <template slot-scope="scope">
          <el-avatar
            :src="
              scope.row.avatar
                ? '/api' + scope.row.avatar
                : 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
            "
          ></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="college" label="学院"></el-table-column>
      <el-table-column prop="nickName" label="姓名"></el-table-column>
      <el-table-column prop="userName" label="工号"></el-table-column>
      <el-table-column prop="roleName" align="center" label="角色名称">
        <template slot-scope="scope">
          <el-tag
            type="primary"
            style="margin-right: 8px; margin-bottom: 8px"
            v-for="(item, index) in scope.row.roles"
            :key="index"
            >{{ item.roleName }}</el-tag
          >
        </template>
      </el-table-column>
      
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.status == 1">正常</el-tag>
          <el-tag type="danger" v-else>禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作" width="280">
        <template slot-scope="scope">
          <el-button type="text" @click="preRole(scope.row)"
            >分配角色</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="resetPassword(scope.row)"
            >重置密码</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="edit(scope.row)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm
            title="是否确认删除当前数据"
            @confirm="del(scope.row.userId)"
          >
            <el-button type="text" slot="reference" style="color: red"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div
      style="
        display: flex;
        justify-content: flex-end;
        height: 47px;
        align-items: center;
      "
    >
      <el-pagination
        layout="total,sizes,prev,pager,next,jumper"
        background
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :total="total"
        @current-change="currentChange"
        @size-change="sizeChange"
      />
    </div>
    <el-dialog
      :visible.sync="visibleFlag"
      @close="close"
      width="40%"
      title="提示"
    >
      <div>
        <el-form :model="user" label-width="80px" :rules="rules" ref="form">
          <el-form-item prop="college" label="学院">
            <el-input placeholder="请输入用户学院" v-model="user.college"></el-input>
          </el-form-item>
          <el-form-item prop="username" label="工号">
            <el-input
              placeholder="请输入工号"
              v-model="user.userName"
            ></el-input>
            <el-input
              placeholder="请输入用户名称"
              disabled
              value="初始密码为工号"
            ></el-input>
          </el-form-item>
          <el-form-item prop="nickName" label="用户名称">
            <el-input placeholder="请输入用户名称" v-model="user.nickName"></el-input>
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input placeholder="请输入邮箱" v-model="user.email"></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="phone">
            <el-input
              placeholder="请输入手机号"
              v-model="user.phone"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio v-model="user.status" :label="0">禁用</el-radio>
            <el-radio v-model="user.status" :label="1">正常</el-radio>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" style="display: flex; justify-content: flex-end">
        <el-button
          type="default"
          style="width: 90px"
          @click="visibleFlag = false"
          >取消</el-button
        >
        <el-button type="primary" style="width: 90px" @click="submit"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      :visible="roleFlag"
      width="35%"
      title="分配角色"
      :show-close="false"
    >
      <div>
        <el-tree
          :default-expand-all="true"
          ref="tree"
          show-checkbox
          :props="defaultProps"
          :data="roleData"
          node-key="roleId"
          empty-text="当前暂无角色"
          check-strictly
        >
        </el-tree>
      </div>
      <div slot="footer" style="display: flex; justify-content: flex-end">
        <el-button type="default" style="width: 90px" @click="roleFlag = false"
          >取消</el-button
        >
        <el-button type="primary" style="width: 90px" @click="submitTree"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Users",
    data() {
      return {
        keyword: "",
        selectFlag: true,
        visibleFlag: false,
        user: {
          userName: "",
          email: "",
          phone: "",
          status: 1
        },
        rules: {
          userName: [{
            required: true,
            message: "请输入用户名称",
            trigger: "blur",
          },
          //
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱号",
            trigger: "blur",
          },
          {
            pattern: /\w+\@(\w+)\.(com|cn)/,
            message: "请输入正确的邮箱",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: "请选择状态",
            trigger: "blur",
          },
        ],
      },
      pageSize: 10,
      page: 1,
      total: 0,
      tableData: [],
      preSelect: [],
      roleFlag: false,
      roleData: [],
      defaultProps: {
        children: "children",
        label: "roleName",
      },
      setUserId: 0,
    };
  },
  methods: {
    resetPassword(data) {
      this.$confirm(
        "将重置用户【" + data.userName + "】的密码为初始密码工号，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then((res) => {
          this.$post("/api/user/reset/" + data.userId).then((res) => {
            if (res.code == 200) {
              this.$message.success(
                "已将用户【" + data.userName + "】的密码重置为工号！"
              );
              this.initPage();
            }
          });
        })
        .catch((action) => {
          this.$message.info("取消重置当前用户密码");
        });
    },
    getRole() {
      this.$get("/api/role/list", {
        limit: 10000,
        page: 1,
      }).then((res) => {
        if (res.code == 200) this.roleData = res.data.records;
      });
    },
    preRole(data) {
      let thizz = this;
      thizz.roleFlag = true;
      setTimeout((_) => {
        thizz.$nextTick((_) => {
          thizz.setUserId = data.userId;
          let arr = [];
          data.roles.map((item) => {
            arr.push(item.roleId);
          });
          thizz.$refs["tree"].setCheckedKeys(arr);
        });
      }, 100);
    },
    submitTree() {
      let ids = this.$refs["tree"].getCheckedKeys();
      this.$post("/api/user/auth/" + this.setUserId, ids.toString()).then(
        (res) => {
          if (res.code == 200) {
            this.roleFlag = false;
            this.initPage();
            this.$message.success("角色分配成功");
          }
        }
      );
    },
    initPage() {
      this.$get("/api/user/list", {
        limit: this.pageSize,
        page: this.page,
        name: this.keyword,
      }).then((res) => {
        if (res.code == 200) {
          let obj = res.data;
          this.pageSize = obj.size;
          this.total = obj.total;
          this.page = obj.current;
          this.tableData = obj.records;
        }
      });
    },
    edit(data) {
      this.user = JSON.parse(JSON.stringify(data));
      this.visibleFlag = true;
    },
    delSelect() {
      let arr = [];
      this.preSelect.map((item) => {
        arr.push(item.userId);
      });
      this.del(arr);
    },
    del(data) {
      let ids = Array.isArray(data) ? data.toString() : data;
      this.$post("/api/user/delete/" + ids).then((res) => {
        if (res.code == 200) {
          this.$message.success("删除成功");
          this.initPage();
        }
      });
    },
    selectAll(selection) {
      this.preSelect = selection;
      this.selectFlag = selection.length > 0 ? false : true;
    },
    selectCheck(selection, row) {
      this.preSelect = selection;
      this.selectFlag = selection.length >= 2 ? false : true;
    },
    currentChange(page) {
      this.page = page;
      this.initPage();
    },
    sizeChange(size) {
      this.pageSize = size;
      this.initPage();
    },
    submit() {
      this.$refs["form"].validate((flag) => {
        if (flag) {
          this.$post(
            "/api/user/" + (this.user.userId ? "update" : "save"),
            this.user
          ).then((res) => {
            console.log(res.code);
            if (res.code == 200) {
              this.$message.success(this.user.userId ? "更新成功" : "添加成功");
              this.initPage();
              this.close();
              this.user = {
                status: 1,
              };
            } else this.$message.warning(res.msg);
          });
        }
      });
    },
    close() {
      this.visibleFlag = false;
      this.roles = {
        userName: "",
        email: "",
        phone: "",
        status: "",
      };
    },
  },
  created() {
    this.initPage();
    this.getRole();
  },
};
</script>

<style scoped>
.mybox >>> .el-table__header,
.mybox >>> .el-table__body {
  margin: 0;
}
</style>
